package com.hulushuju.core.util;

import com.hulushuju.core.net.ContentType;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Objects;
import java.util.Random;

/**
 * @Author: Hanjiafeng
 * @Date: 2019-05-29
 * @Desc: 文件管理器
 */
public class FileManager {

    /**
     * 随机对象
     */
    private final static Random RANDOM = new Random();

    /**
     * 创建一个新文件,并写入内容
     *
     * @param flag     添加在开头的标记字符串,如果为null,不添加
     * @param content  文件内容
     * @param fileType 文件格式
     */
    public static void writeNew(String flag, String content, String fileType) {
        //todo 写入文件路径
        String fileName = generateFileName() + "." + fileType;
        if (!Objects.isNull(flag)) {
            fileName = "[" + flag + "]" + fileName;
        }
        String filePath = getPath();
        fileName = filePath + fileName;
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName)))) {
            writer.write(content);
            writer.flush();
        } catch (IOException e) {
            //todo 写入日志
            e.printStackTrace();
        }
    }

    /**
     * 使用当前时间和随机数生成文件名
     *
     * @return 文件名
     */
    public static String generateFileName() {
        String firstPart = Long.toString(System.currentTimeMillis());
        String secondPart = Float.toString(RANDOM.nextFloat() * 10_000_000);
        secondPart = secondPart.substring(0, 6);
        return String.join("_", firstPart, secondPart);
    }

    private static String getPath() {
        return "F://";
    }
}
